package com.imc.griebeler.prs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;

public class Driver {
	public static void main(String[] args) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

		System.out.print("Enter your name: ");
		Player human = new Player(reader.readLine());

		Player computer = new Player("computer"); 

		PaperRockScissorsGame game = new PaperRockScissorsGame();
		int round = 0;
		while (true) {
			round++;
			System.out.println("---------");
			System.out.println("Round " + round);
			Symbol humanSymbol = getInput(reader);
			if (humanSymbol == null) {
				quitGame(human);
				break;
			}
			PlayerGuess humanGuess = new PlayerGuess(human, humanSymbol);
			PlayerGuess computerGuess = new PlayerGuess(computer, randomSymbol());
			Player winner = game.guess(humanGuess, computerGuess);
			System.out.println(humanGuess.getPlayer().getName() + " guessed: " + humanGuess.getGuess());
			System.out.println(computerGuess.getPlayer().getName() + " guessed: " + computerGuess.getGuess());
			if(null == winner) {
				System.out.println("Tie");
				continue;
			}
				
			System.out.println("Winner: " + winner.getName());
			if(human.equals(winner)) {
				human.addWin();
				computer.addLoss();
			}else {
				human.addLoss();
				computer.addWin();
			}
		}
	}

	private static Symbol randomSymbol() {
		Random random = new Random();
		return Symbol.values()[random.nextInt(3)];
	}

	public static Symbol getInput(BufferedReader reader) throws IOException {
		System.out.print("Enter your guess [PAPER, ROCK, SCISSORS or QUIT]: ");
		String input = reader.readLine();
		if (input.equalsIgnoreCase("QUIT"))
			return null;
		else {
			Symbol result = Symbol.byRelaxedInput(input);
			if (null == result) {
				System.out.println("Invalid entry");
				result = getInput(reader);
			}
			return result;
		}
	}

	private static void quitGame(Player human) {
		System.out.println(human.getName() + ", your final tally: " + human.getWins() + " wins and " + human.getLosses() + " losses.");
	}
}
